package com.nobuyme.box;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.nobuyme.box.account.Account;
import com.nobuyme.box.account.AccountManager;
import com.nobuyme.box.app.UrlCenter;
import com.nobuyme.box.bean.BannerBean;
import com.nobuyme.box.bean.InitIdEntity;
import com.nobuyme.box.toy.ToyManageActivity;
import com.nobuyme.box.toy.ToyRentActivity;
import com.nobuyme.box.toy.ToyReturnActivity;
import com.nobuyme.box.toy.UserHelpActivity;
import com.nobuyme.box.toy.VideoPlayActivity;
import com.nobuyme.box.util.SilentInstall;
import com.nobuyme.box.util.StrokeTextView;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.HttpRequest;
import com.pachong.android.framework.httprequest.ResponseParser;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.utils.EasyToast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;


public class MainActivity extends BaseActivity implements OnItemClickListener {

    @Bind(R.id.convenientBanner)
    ConvenientBanner mConvenientBanner;
    @Bind(R.id.package_num)
    StrokeTextView mPackageNum;
    private List<BannerBean> list;

    private int polling_one;
    private int polling_two;
    private int polling_three;
    private int polling_four;

    private final static String APKURL = "http://or84r4lrb.bkt.clouddn.com/toyBox-1.0.0-debug.apk";

    final static String LOCAL_APK_NAME = Environment.getExternalStorageDirectory().getAbsolutePath() +
            File.separator + "apkName.apk";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        hideToolbar();
//        getBannerData();
        getInnerPath();
        try {
            String pkName = this.getPackageName();
            mPackageNum.setText("Version:"+getPackageManager().getPackageInfo(pkName, 0).versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

    }


    public static void start(Activity activity) {
        Intent intent = new Intent(activity, MainActivity.class);
        activity.startActivity(intent);
    }

    private void getInnerPath() {
        StringBuilder log = new StringBuilder();
        String inPath = getInnerSDCardPath();
        log.append("内置SD卡路径：" + inPath + "\r\n");
        String allPath = inPath + "/initdata/toyboxID.txt";
        Log.e("内置SD卡路径", allPath);
        //打开文件
        File file = new File(allPath);
        //如果path是传递过来的参数，可以做一个非目录的判断
        if (file.isDirectory()) {
            Log.e("TestFile", "未找到初始化文件");
        } else {
            try {
                String content = ""; //文件内容字符串
                InputStream instream = new FileInputStream(file);

                if (instream != null) {
                    InputStreamReader inputreader = new InputStreamReader(instream);
                    BufferedReader buffreader = new BufferedReader(inputreader);
                    String line;
                    //分行读取
                    try {
                        while ((line = buffreader.readLine()) != null) {
                            content += line + "\n";
                            //从配置文件保存toyBox信息
                            if (TextUtils.isEmpty(content)) {
                                EasyToast.showToast(this, "初始化文件为空");
                            } else {
                                ResponseParser parser = new ResponseParser(InitIdEntity.class);
                                parser.setJsonString(content.trim());
                                try {
                                    JSONObject jsonObject = new JSONObject(content.trim());

                                    int id = (int) jsonObject.get("id");
                                    polling_one = (int) jsonObject.get("polling_one");
                                    polling_two = (int) jsonObject.get("polling_two");
                                    polling_three = (int) jsonObject.get("polling_three");
                                    polling_four = (int) jsonObject.get("polling_four");
                                    Account acc = AccountManager.getCurrentAccount();
                                    acc.setId(id);
                                    acc.setPolling_one(polling_one);
                                    acc.setPolling_two(polling_two);
                                    acc.setPolling_three(polling_three);
                                    acc.setPolling_four(polling_four);
                                    initToyData();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        instream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e("TestFile", e.getMessage());
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                EasyToast.showToast(this, "未找到初始化文件");
            }
        }
        List<String> extPaths = getExtSDCardPath();
        for (String path : extPaths) {
            Log.e("外置SD卡路径", path);
        }
        System.out.println(log.toString());
    }


    private void initToyData() {
        Account acc = AccountManager.getCurrentAccount();
        //设置极光id
        JPushInterface.setAlias(MainActivity.this, acc.getId() + "", null);
        HttpRequest request = new HttpRequest(this);
        UrlParams urlParams = new UrlParams();
        String allUrl = String.format(UrlCenter.USER_INFO, acc.getId());
        urlParams.put("param", acc.getId() + "");
        request.get(allUrl, urlParams, new DataRequestListener<Account>(Account.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(Account o) {
                super.onSuccess(o);
                //讲id 和 地址保存下来
//                AccountManager.setCurrentAccount(o);
                Account acc = AccountManager.getCurrentAccount();
                acc.setName(o.getName());
                acc.setToybox_code(o.getToybox_code());
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });

    }


    /**
     * 获取内置SD卡路径
     *
     * @return
     */
    public String getInnerSDCardPath() {
        return Environment.getExternalStorageDirectory().getPath();
    }

    /**
     * 获取外置SD卡路径
     *
     * @return 应该就一条记录或空
     */
    public List<String> getExtSDCardPath() {
        List<String> lResult = new ArrayList<String>();
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("mount");
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains("extSdCard")) {
                    String[] arr = line.split(" ");
                    String path = arr[1];
                    File file = new File(path);
                    if (file.isDirectory()) {
                        lResult.add(path);
                    }
                }
            }
            isr.close();
        } catch (Exception e) {
        }
        return lResult;
    }


    //获得轮播信息
    private void getBannerData() {
        HttpRequest request = new HttpRequest(this);
        request.get(UrlCenter.BANNER_LIST, null, new DataRequestListener<List<BannerBean>>(BannerBean.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(List<BannerBean> o) {
                super.onSuccess(o);
                list = o;
                setBannerData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    //设置轮播
    private void setBannerData(List<BannerBean> o) {
        if (mConvenientBanner != null) {
            mConvenientBanner.setPages(new CBViewHolderCreator() {
                @Override
                public LocalImageHolderView createHolder() {
                    return new LocalImageHolderView();
                }
            }, o)
                    .setPointViewVisible(true)    //设置指示器是否可见
                    //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                    .setPageIndicator(new int[]{R.mipmap.unrmal, R.mipmap.unnormal})
                    .setOnItemClickListener(this)  //点击监听
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
//                  mConvenientBanner.setManualPageable(false);
        }
    }

    @Override
    public void onItemClick(int position) {
        switch (position) {
            case 0:
                VideoPlayActivity.start(MainActivity.this);
                break;
        }
    }


    private class LocalImageHolderView implements Holder<BannerBean> {
        private ImageView mIvBanner;
        private VideoView mBannerVideoView;

        @Override
        public View createView(Context context) {
            //你可以通过layout文件来创建，不一定是Image，任何控件都可以进行翻页
            View inflate = LayoutInflater.from(context).inflate(R.layout.banner_item_bg, null);
            mIvBanner = (ImageView) inflate.findViewById(R.id.iv_banner);
            mBannerVideoView = (VideoView) inflate.findViewById(R.id.banner_videoView);
//            tv_time = (TextView) inflate.findViewById(R.id.tv_main_time);
            return inflate;
        }

        @Override
        public void UpdateUI(Context context, int position, BannerBean data) {
            BannerBean bannerBean = list.get((position + list.size() - 1) % list.size());
            if (data.getType().equals("video")) {
                mIvBanner.setVisibility(View.GONE);
                mBannerVideoView.setVideoPath(data.getUrl());
                mBannerVideoView.start();
                mConvenientBanner.startTurning(bannerBean.getDuration() * 1000);
                Log.e("data.getDuration()", data.toString());

            } else if (data.getType().equals("image")) {
                mBannerVideoView.setVisibility(View.GONE);
                Glide.with(MainActivity.this).load(data.getUrl()).into(mIvBanner);
                mConvenientBanner.startTurning(bannerBean.getDuration() * 1000);
                Log.e("data.getDuration()1", data.toString());
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        getBannerData();
    }

    @Override
    public void onPause() {
        super.onPause();
        mConvenientBanner.stopTurning();
    }


    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_main, null);
    }

    @OnClick({R.id.btn_help, R.id.btn_manage, R.id.btn_return, R.id.btn_rent
//            , R.id.button
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_help:
                UserHelpActivity.start(this);
                break;
            case R.id.btn_manage:
                ToyManageActivity.start(this);

                break;
            case R.id.btn_return:
                ToyReturnActivity.start(this);
                break;
            case R.id.btn_rent:
                ToyRentActivity.start(this);
                break;
//            case R.id.button:
//                AppUpdateThread.startDownloade(APKURL,APKURL, LOCAL_APK_NAME, new AppUpdateThread.OnProgressListener() {
//                    @Override
//                    public void onSuccess(boolean isSuccess) {
//                        if (isSuccess == false){
//                        }else if (isSuccess) {
//                            new Thread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    AppUpdateThread.silentInstall(LOCAL_APK_NAME);
//                                    rebootSU();
//                                }
//                            }).start();
//                        };
//                        }
//                });
//                break;


        }
    }

    public void onSilentInstall(String apk_Path) {
        if (!isRoot()) {
            Log.e("apk文件", "没有ROOT权限，不能使用秒装");
//            Toast.makeText(this, "没有ROOT权限，不能使用秒装", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(apk_Path)) {
            Log.e("apk文件", "请选择安装包！");
//            Toast.makeText(this, "请选择安装包！", Toast.LENGTH_SHORT).show();
            return;
        }
//        mButton.setText("安装中");
        new Thread(new Runnable() {
            @Override
            public void run() {
                SilentInstall installHelper = new SilentInstall();
                final boolean result = installHelper.install(LOCAL_APK_NAME);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result) {

                            Toast.makeText(MainActivity.this, "安装成功！", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "安装失败！", Toast.LENGTH_SHORT).show();
                        }
//                        mButton.setText("秒装");
                    }
                });

            }
        }).start();

    }


    /**
     * 判断手机是否拥有Root权限。
     *
     * @return 有root权限返回true，否则返回false。
     */
    public boolean isRoot() {
        boolean bool = false;
        try {
            bool = new File("/system/bin/su").exists() || new File("/system/xbin/su").exists();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bool;
    }


}
